<template>
  <div class="product-management">
    <h2>{{ t('admin.menu.products') }}</h2>
    <p>{{ t('admin.products.description') }}</p>
    
    <!-- Product management controls -->
    <el-card class="management-card">
      <template #header>
        <div class="card-header">
          <span>{{ t('admin.products.productList') }}</span>
          <el-button type="primary" @click="openProductForm">
            {{ t('admin.products.addProduct') }}
          </el-button>
        </div>
      </template>
      
      <!-- Search and filter -->
      <div class="filter-section">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-input 
              v-model="filters.name" 
              :placeholder="t('admin.products.name')"
              clearable
            />
          </el-col>
          <el-col :span="6">
            <el-select 
              v-model="filters.category" 
              :placeholder="t('admin.products.category')"
              clearable
              style="width: 100%"
            >
              <el-option 
                v-for="category in categories" 
                :key="category.value" 
                :label="category.label"
                :value="category.value">
              </el-option>
            </el-select>
          </el-col>
          <el-col :span="6">
            <el-select 
              v-model="filters.status" 
              :placeholder="t('admin.products.status')"
              clearable
              style="width: 100%"
            >
              <el-option 
                v-for="status in statuses" 
                :key="status.value" 
                :label="t(`admin.products.status.${status.value.toLowerCase()}`)"
                :value="status.value">
              </el-option>
            </el-select>
          </el-col>
          <el-col :span="6">
            <el-button type="primary" @click="searchProducts">
              {{ t('common.search') }}
            </el-button>
            <el-button @click="resetFilters">
              {{ t('common.reset') }}
            </el-button>
          </el-col>
        </el-row>
      </div>
      
      <!-- Product table -->
      <el-table :data="products" style="width: 100%" v-loading="loading">
        <el-table-column prop="id" :label="t('admin.products.id')" width="80"></el-table-column>
        <el-table-column prop="name" :label="t('admin.products.name')"></el-table-column>
        <el-table-column prop="category" :label="t('admin.products.category')"></el-table-column>
        <el-table-column prop="price" :label="t('admin.products.price')"></el-table-column>
        <el-table-column prop="stockQuantity" :label="t('admin.products.stockQuantity')"></el-table-column>
        <el-table-column :label="t('admin.products.status')">
          <template #default="scope">
            <el-tag 
              :type="scope.row.status === 'ACTIVE' ? 'success' : 'warning'" 
              disable-transitions
            >
              {{ t(`admin.products.status.${scope.row.status.toLowerCase()}`) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column :label="t('common.actions')" width="200">
          <template #default="scope">
            <el-button size="small" @click="viewProduct(scope.row)">
              {{ t('common.view') }}
            </el-button>
            <el-button size="small" @click="editProduct(scope.row)">
              {{ t('common.edit') }}
            </el-button>
            <el-button size="small" type="danger" @click="deleteProduct(scope.row)">
              {{ t('common.delete') }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- Pagination -->
      <div class="pagination-section">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    
    <!-- Product form dialog -->
    <el-dialog 
      v-model="dialogVisible" 
      :title="dialogTitle" 
      width="600px"
      @close="resetProductForm"
    >
      <el-form 
        :model="productForm" 
        :rules="productRules" 
        ref="productFormRef" 
        label-width="120px"
      >
        <el-form-item :label="t('admin.products.name')" prop="name">
          <el-input v-model="productForm.name"></el-input>
        </el-form-item>
        <el-form-item :label="t('admin.products.description')" prop="description">
          <el-input 
            v-model="productForm.description" 
            type="textarea"
            :rows="3"
          ></el-input>
        </el-form-item>
        <el-form-item :label="t('admin.products.imageUrl')" prop="imageUrl">
          <el-input v-model="productForm.imageUrl"></el-input>
        </el-form-item>
        <el-form-item :label="t('admin.products.price')" prop="price">
          <el-input-number 
            v-model="productForm.price" 
            :precision="2" 
            :step="0.01" 
            :min="0"
          ></el-input-number>
        </el-form-item>
        <el-form-item :label="t('admin.products.stockQuantity')" prop="stockQuantity">
          <el-input-number 
            v-model="productForm.stockQuantity" 
            :min="0"
          ></el-input-number>
        </el-form-item>
        <el-form-item :label="t('admin.products.category')" prop="category">
          <el-select v-model="productForm.category" style="width: 100%">
            <el-option 
              v-for="category in categories" 
              :key="category.value" 
              :label="category.label"
              :value="category.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item :label="t('admin.products.status')" prop="status">
          <el-select v-model="productForm.status" style="width: 100%">
            <el-option 
              v-for="status in statuses" 
              :key="status.value" 
              :label="t(`admin.products.status.${status.value.toLowerCase()}`)"
              :value="status.value">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">{{ t('common.cancel') }}</el-button>
          <el-button type="primary" @click="saveProduct">{{ t('common.save') }}</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue'
import { useI18n } from 'vue-i18n'
import { ElMessage } from 'element-plus'
import { productAPI, commonAPI } from '@/utils/api'

export default {
  name: 'ProductManagement',
  setup() {
    const { t } = useI18n()
    const loading = ref(false)
    const dialogVisible = ref(false)
    const dialogTitle = ref('')
    const productFormRef = ref(null)
    
    const products = ref([])
    const selectedProducts = ref([])
    
    const filters = reactive({
      name: '',
      category: '',
      status: ''
    })
    
    const pagination = reactive({
      currentPage: 1,
      pageSize: 10,
      total: 0
    })
    
    const productForm = reactive({
      id: null,
      name: '',
      description: '',
      imageUrl: '',
      price: 0,
      stockQuantity: 0,
      category: '',
      status: 'ACTIVE'
    })
    
    const categories = ref([
      { value: 'electronics', label: t('admin.products.categories.electronics') },
      { value: 'clothing', label: t('admin.products.categories.clothing') },
      { value: 'books', label: t('admin.products.categories.books') },
      { value: 'home', label: t('admin.products.categories.home') },
      { value: 'sports', label: t('admin.products.categories.sports') }
    ])
    
    const statuses = ref([
      { value: 'ACTIVE', label: t('admin.products.status.active') },
      { value: 'INACTIVE', label: t('admin.products.status.inactive') }
    ])
    
    const productRules = {
      name: [
        { required: true, message: t('admin.products.enterProductName'), trigger: 'blur' }
      ],
      price: [
        { required: true, message: t('admin.products.enterPrice'), trigger: 'blur' }
      ],
      stockQuantity: [
        { required: true, message: t('admin.products.enterStockQuantity'), trigger: 'blur' }
      ],
      category: [
        { required: true, message: t('admin.products.selectCategory'), trigger: 'blur' }
      ],
      status: [
        { required: true, message: t('admin.products.selectStatus'), trigger: 'blur' }
      ]
    }
    
    const loadProducts = async () => {
      try {
        loading.value = true
        
        // 构建请求参数
        const params = {
          ...commonAPI.formatFilters(filters),
          ...commonAPI.formatPagination(pagination)
        }
        
        // 调用 API 获取产品列表
        const response = await productAPI.getProducts(params)
        products.value = response.data.content || response.data || []
        pagination.total = response.data.totalElements || response.data.length || 0
        
      } catch (error) {
        console.error('Error loading products:', error)
        ElMessage.error(t('admin.products.errorLoadingProducts'))
      } finally {
        loading.value = false
      }
    }
    
    const searchProducts = () => {
      pagination.currentPage = 1  // 重置到第一页
      loadProducts()
    }
    
    const resetFilters = () => {
      filters.name = ''
      filters.category = ''
      filters.status = ''
      pagination.currentPage = 1
      loadProducts()
    }
    
    const openProductForm = () => {
      dialogTitle.value = t('admin.products.addProduct')
      resetProductForm()
      dialogVisible.value = true
    }
    
    const editProduct = async (product) => {
      try {
        dialogTitle.value = t('admin.products.editProduct')
        // 如果需要获取完整的产品详情，可以调用API
        const response = await productAPI.getProduct(product.id)
        Object.assign(productForm, response.data)
        dialogVisible.value = true
      } catch (error) {
        console.error('Error loading product details:', error)
        ElMessage.error(t('admin.products.errorLoadingProductDetails'))
      }
    }
    
    const viewProduct = async (product) => {
      try {
        dialogTitle.value = t('admin.products.viewProduct')
        const response = await productAPI.getProduct(product.id)
        Object.assign(productForm, response.data)
        // 禁用编辑模式
        dialogVisible.value = true
      } catch (error) {
        console.error('Error loading product details:', error)
        ElMessage.error(t('admin.products.errorLoadingProductDetails'))
      }
    }
    
    const deleteProduct = async (product) => {
      try {
        await productAPI.deleteProduct(product.id)
        ElMessage.success(t('admin.products.productDeleted'))
        loadProducts() // 重新加载列表
      } catch (error) {
        console.error('Error deleting product:', error)
        ElMessage.error(t('admin.products.errorDeletingProduct'))
      }
    }
    
    const saveProduct = async () => {
      await productFormRef.value.validate(async (valid) => {
        if (valid) {
          try {
            if (productForm.id) {
              // 更新现有产品
              await productAPI.updateProduct(productForm.id, productForm)
              ElMessage.success(t('admin.products.productUpdated'))
            } else {
              // 创建新产品
              await productAPI.createProduct(productForm)
              ElMessage.success(t('admin.products.productCreated'))
            }
            dialogVisible.value = false
            loadProducts() // 重新加载列表
          } catch (error) {
            console.error('Error saving product:', error)
            ElMessage.error(t('admin.products.errorSavingProduct'))
          }
        }
      })
    }
    
    const resetProductForm = () => {
      Object.keys(productForm).forEach(key => {
        if (key === 'id') {
          productForm[key] = null
        } else if (key === 'price') {
          productForm[key] = 0
        } else if (key === 'stockQuantity') {
          productForm[key] = 0
        } else if (key === 'status') {
          productForm[key] = 'ACTIVE'
        } else if (key === 'category') {
          productForm[key] = ''
        } else {
          productForm[key] = ''
        }
      })
    }
    
    const handleSelectionChange = (selection) => {
      selectedProducts.value = selection
    }
    
    const handleSizeChange = (val) => {
      pagination.pageSize = val
      loadProducts()
    }
    
    const handleCurrentChange = (val) => {
      pagination.currentPage = val
      loadProducts()
    }
    
    onMounted(() => {
      loadProducts()
    })
    
    return {
      t,
      loading,
      dialogVisible,
      dialogTitle,
      productFormRef,
      products,
      selectedProducts,
      filters,
      pagination,
      productForm,
      categories,
      statuses,
      productRules,
      loadProducts,
      searchProducts,
      resetFilters,
      openProductForm,
      editProduct,
      viewProduct,
      deleteProduct,
      saveProduct,
      resetProductForm,
      handleSelectionChange,
      handleSizeChange,
      handleCurrentChange
    }
  }
}
</script>

<style scoped>
.product-management {
  padding: 20px;
}

.management-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.filter-section {
  margin-bottom: 20px;
  padding: 20px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.pagination-section {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>